﻿using System;
using System.Data;
using System.Threading;
using System.Data.Common;
using System.Collections.Generic;

namespace LeanEngine.Data
{
    /// <summary>
    /// Represents a Transact-SQL transaction made in the database. 
    /// </summary>
    public sealed class DataTransaction : IDisposable
    {
        #region Declaration Members

        private DbConnection _connection;

        #endregion

        #region PropertyInfo Members

        /// <summary>
        /// Gets the Transact-SQL class internally used
        /// </summary>
        internal DbTransaction Transaction
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the connection object associated with the transaction
        /// </summary>
        internal DbConnection Connection
        {
            get { return _connection; }
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Initialize a new instance of LeanEngine.Data.Common.DataTransaction class.
        /// </summary>
        /// <exception cref="System.InvalidOperationException"></exception>
        public DataTransaction()
        {
            lock (this)
            {
                if (DataTransactionPool.HasTransaction())
                {
                    throw new InvalidOperationException("Nested transactions is not allowed.");
                }

                this._connection = DataProvider.NewConnection();
                this._connection.Open();

                this.Transaction = this._connection.BeginTransaction();
                DataTransactionPool.BeginTransaction(this);
            }
        }

        #endregion

        #region Method Members

        /// <summary>
        /// Commits the database transaction.
        /// </summary>
        /// <exception cref="System.Exception">An error occurred while trying to commit the transaction.</exception>
        /// <exception cref="System.InvalidOperationException">The transaction has already been committed or rolled back.  -or- The connection is broken.</exception>
        public void Complete()
        {
            if (this._connection != null)
            {
                try
                {
                    Transaction.Commit();
                    Transaction.Dispose();
                    Transaction = null;

                    DataTransactionPool.ReleaseTransaction();
                }
                catch
                {
                    Rollback();
                    throw;
                }
                finally
                {
                    ReleaseConnection();
                }
            }
        }

        private void Rollback()
        {
            if (this._connection != null)
            {
                try
                {
                    Transaction.Rollback();
                }
                finally
                {
                    Transaction.Dispose();
                    Transaction = null;

                    DataTransactionPool.ReleaseTransaction();

                    ReleaseConnection();
                }
            }
        }

        private void ReleaseConnection()
        {
            this._connection.Close();
            this._connection.Dispose();
            this._connection = null;
        }

        #endregion

        #region IDisposable Members

        /// <summary>
        /// Release all the resources used 
        /// </summary>
        public void Dispose()
        {
            if (Transaction != null)
            {
                Rollback();
            }
        }

        #endregion
    }
}
